<!--
 * @Author: ljc
 * @Date: 2023-06-07
 * @Description: 单位管理
-->
<template>
  <RkContainer :isFooter="false"
    :isHeader="true"
    :isAside="isAside">
    <template #header_left></template>
    <template #header_right>
      <el-button type="primary"
        @click="handleAdd">新增</el-button>
      <el-button @click="handleTemplate">模板下载</el-button>
      <el-button @click="handleImport">单位导入</el-button>
      <el-button @click="handleExports">导出</el-button>
      <el-button @click="handleRefresh">刷新缓存</el-button>
    </template>
    <template #aside>
      <RkAdAgTree :adTreeHidden="false"
        @adNodeClick="handleAdNodeClick"
        @agNodeClick="handleAgNodeClick"
        @adCurrentChange="handleAdNodeChange"
        @toggleHidden="(hidden) => isAside = !hidden" />
    </template>
    <template #main>
      <rk-center>
        <template #content>
          <rk-grid ref="unitViewRef"
            :title="route.meta.title"
            :dataUrl="'/pubAgency/getPubAgencyPageList'"
            :columns="tableColumns"
            :params="queryParams">
            <template #toolbar_title_buttons>
              <el-input v-model="queryParams.keyword"
                placeholder="请输入单位名称/统一社会信用代码"
                class="mr-12"
                style="width: 240px;"
                clearable
                @input="handleSearch">
              </el-input>
              <rk-select style="width: 100px;"
                :isSearch="false"
                placeholder="请选择"
                enum="UNIT_STATUS_ENUMS"
                v-model="queryParams.status"
                @change="handleSearch">
              </rk-select>
            </template>
            <template #operation="{ row }">
              <el-dropdown>
                <span class="el-dropdown-link">
                  更多操作
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(row)">修改</el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(row)">删除</el-dropdown-item>
                    <el-dropdown-item @click="handleOpenStop(row)">{{ row.status === '1' ? '停用' : '启用' }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </rk-grid>
        </template>
      </rk-center>
    </template>
    <unit-form-dialog ref="unitFormDialogRef"
      @confirm="handleSearch"></unit-form-dialog>
    <unit-using-dialog ref="unitUsingDialogRef"
      @confirm="handleSearch"></unit-using-dialog>
    <!-- <rk-import-modal ref="rkImportModalRef"
    action="/pubAgency/importExcelForPubagencyInfo"
    title="单位导入"
    :success="handleSuccess"></rk-import-modal> -->
  </RkContainer>
</template>
<script setup>
import { ArrowDown } from '@element-plus/icons-vue'
import { useContainerAside } from '@/hooks'
import { operationColumn } from '@/config/column-config.js'
import { useRoute } from 'vue-router'
import UnitFormDialog from './dialogs/UnitFormDialog.vue'
import UnitUsingDialog from './dialogs/UnitUsingDialog.vue'
import { UNIT_STATUS_ENUMS } from '@/enums/enums-system.js'
import { ref } from 'vue'
import { RkConfirmBox } from '@/components/message-box/index.js'
import { ElLoading, ElMessage } from 'element-plus'
import { dowloadFile, fileType } from '@/utils/file-utils.js';
import { getCurrentInstance } from 'vue'
import { useUnitApi } from '@/api/index.js'

const { deletePubAgency, getPubAgencyByGuid, exportPubagencyInfo, downloadTemplate, refreshSysAdCache } = useUnitApi();
const { appContext } = getCurrentInstance()
const globalProxy = appContext.config.globalProperties;

// ----- 获取当前路由
const route = useRoute()
// ----- 树结构操作
const { isAside } = useContainerAside()
// ----- 表格相关操作
const queryParams = ref({
  keyword: undefined,
  adCode: undefined,
  agCode: undefined,
  status: undefined,
  name: undefined,
  superguid: undefined,
  levelno: undefined,
  code: undefined,
  supdep: undefined,
  adMdiv: undefined
})
//传值方法
provide('treeParams', queryParams.value)
let leaf = ref(false)
const unitViewRef = ref('')
const unitFormDialogRef = ref('')
const unitUsingDialogRef = ref('')
const tableColumns = ref([
  { field: 'code', title: '单位编码', width: 180, align: 'left' },
  { field: 'name', title: '单位名称', width: 250, align: 'left' },
  { field: 'alias', title: '简称', width: 200, align: 'center' },
  { field: 'supdep', title: '主管部门', width: 200, align: 'left' },
  { field: 'zwdwlx', title: '单位类型', width: 200, align: 'left' },
  { field: 'bmfl', title: '部门分类', width: 150, align: 'left' },
  { field: 'province', title: '区划', width: 100, align: 'center' },
  { field: 'levelno', title: '级次', width: 80, align: 'center' },
  {
    field: 'status', title: '状态', width: 80, align: 'center',
    formatter: ['enumsFormats', 'UNIT_STATUS_ENUMS'],
    cellRender: { name: 'enumsRender', enumName: 'UNIT_STATUS_ENUMS', isTag: true }
  },
  { field: 'orgcode', title: '组织机构代码', width: 120, align: 'center' },
  { field: 'usccode', title: '统一社会信用代码', width: 150, align: 'center' },
  { field: 'starttime', title: '生效时间', width: 120, align: 'center' },
  { field: 'endtime', title: '失效时间', width: 120, align: 'center' },
  { field: 'frdb', title: '法人代表', width: 100, align: 'center' },
  { field: 'cwfzr', title: '财务负责人', width: 120, align: 'center' },
  { field: 'tel', title: '联系电话', width: 150, align: 'center' },
  { field: 'address', title: '地址', width: 200, align: 'left' },
  operationColumn()
])
// 区划树变化触发
const handleAdNodeChange = (data, treeNode) => {
  const { id, code, name, parentId, leaf } = data
  queryParams.value.adMdiv = id
  queryParams.value.agId = id
  queryParams.value.adCode = code
  queryParams.value.name = name
  queryParams.value.superguid = ''
  queryParams.value.levelno = undefined
  handleSearch()
}
// 左侧区划树点击
const handleAdNodeClick = (data) => {
  const { id, code, name, parentId, leaf: isLeaf } = data
  queryParams.value.adMdiv = id
  leaf.value = isLeaf
  queryParams.value.agId = id
  queryParams.value.adCode = code
  queryParams.value.agCode = undefined
  queryParams.value.name = name
  queryParams.value.levelno = undefined
  queryParams.value.code = undefined
  queryParams.value.supdep = undefined
  handleSearch()
}
// 左侧单位树点击
const handleAgNodeClick = (data) => {
  const { id, code, name, parentId, leaf: isLeaf, levelno } = data
  queryParams.value.agId = id
  queryParams.value.agCode = code
  leaf.value = isLeaf
  let childLen = data.children.length
  queryParams.value.levelno = levelno + 1
  queryParams.value.code = `00${childLen + 1}`
  queryParams.value.supdep = code.substr(0, 3)
  handleSearch()
}
// 新增
const handleAdd = () => {
  unitFormDialogRef.value.handleOpen({ model: 'add' })
}
//编辑
const handleEdit = (row) => {
  getDetailInfo(row.guid)
}
/** 启用停用操作 */
const handleOpenStop = (row) => {
  unitUsingDialogRef.value.handleOpen({ seleModel: row })
}
//删除
const handleDelete = (row) => {
  let formData = {
    guids: row.guid,
    superguids: row.superguid,
    province: queryParams.value.adCode
  }
  RkConfirmBox({
    title: '提示',
    content: `您确定要删除吗？`,
    onSubmit: async function () {
      const loading = ElLoading.service({ fullscreen: true, text: `删除中,请稍等...` })
      const result = await deletePubAgency(formData)
      const { data, code, msg } = result
      if (code === 200) {
        loading.close()
        ElMessage({
          message: '删除成功！',
          type: 'success',
        })
        handleSearch()
      } else {
        loading.close()
        ElMessage({
          message: `${msg}`,
          type: 'error',
        })
      }
    },
    onCancel: function () {
    }
  })
}
// 获取详情
const getDetailInfo = async (guid) => {
  const result = await getPubAgencyByGuid({ guid })
  const { data, code, msg } = result
  if (code === 200) {
    unitFormDialogRef.value.handleOpen({ model: 'edit', unitModel: data })
  }
}
/**查询 */
const handleSearch = () => {
  unitViewRef.value.searchEvent()
}

/** 单位导入 */
const handleImport = () => {
  globalProxy.$rKImportModalAlert({
    title: '单位导入',
    action: "/pubAgency/importExcelForPubagencyInfo",
    accept: '.xls,.xlsx',
    success: () => {
      handleSearch()
    },
  })
}

/** 模板下载 */
const handleTemplate = async () => {
  ElMessage({
    message: `'文件正在下载中，请稍后！'`,
    type: 'info',
  })
  const loading = ElLoading.service({
    text: '模板下载中...',
  })
  const result = await downloadTemplate({ filename: '单位导入模板.xlsx' })
  if (result) {
    dowloadFile(result, '单位导入模板', fileType.excel)
    loading.close()
  } else {
    loading.close()
  }
}
/** 单位导出 */
const handleExports = async () => {
  ElMessage({
    message: `'文件正在导出，请稍后！'`,
    type: 'info',
  })
  const loading = ElLoading.service({
    text: '导出中...',
  })
  const result = await exportPubagencyInfo(queryParams.value)
  if (result) {
    dowloadFile(result.data, '', fileType.excel, result)
    loading.close()
  } else {
    loading.close()
  }
}
/** 区划刷新 */
const handleRefresh = async () => {
  const result = await refreshSysAdCache({})
  const { data, code, msg } = result
  if (code === 200) {
    ElMessage({
      message: `刷新缓存成功！`,
      type: 'success',
    })
  } else {
    ElMessage({
      message: `刷新缓存失败！`,
      type: 'error',
    })
  }
}

</script>

<style lang="scss" scoped>
</style>